//
//  XJYLoginViewController.m
//  高仿萝卜书摘
//
//  Created by 谢俊逸 on 2016/11/27.
//  Copyright © 2016年 谢俊逸. All rights reserved.
//

#import "XJYLoginViewController.h"
#import "XJYLogin.h"
#import "XJYLoginTextCell.h"
#import "XJYHeader.h"
#import "TPKeyboardAvoidingTableView.h"
#import <LeanCloudSocial/AVOSCloudSNS.h>

@interface XJYLoginViewController ()<UITableViewDataSource, UITableViewDelegate>

@property (nonatomic,strong) XJYLogin *myLogin;

@property (nonatomic,strong) TPKeyboardAvoidingTableView *myTableView;
@property (strong,nonatomic) UIView *bottomView;

//@property (assign,nonatomic) BOOL captchaNeeded;
@property (strong,nonatomic) FUIButton *loginButton, *cannotLoginButton;
@property (strong,nonatomic) UIActivityIndicatorView *activityIndicator;
@property (strong,nonatomic) UIImageView *iconUserView, *bgBlurredView;

@property (strong,nonatomic) UIButton *cancelButton;


@property (strong,nonatomic) UIButton *thirdPartyLoginWeiboButton;
@property (strong,nonatomic) UIButton *thirdPartyLoginWeixinButton;
@property (strong,nonatomic) UIButton *thirdPartyLoginQQButton;


@property (strong,nonatomic) NSString *nameString;
@property (strong,nonatomic) NSString *passwordString;

@end

@implementation XJYLoginViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    _nameString = @"";
    _passwordString = @"";
    
#pragma mark Notification
    
    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(loginFailed) name:@"loginFailed" object:nil];
    
    
    _myTableView = ({
        TPKeyboardAvoidingTableView *tableView = [[TPKeyboardAvoidingTableView alloc]initWithFrame:self.view.bounds style:UITableViewStylePlain];
        [tableView registerClass:[XJYLoginTextCell class] forCellReuseIdentifier:kCellIdentifier_Input_OnlyText_Cell_Text];
        tableView.backgroundView = self.bgBlurredView;
        tableView.dataSource = self;
        tableView.delegate = self;
        tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
        tableView.userInteractionEnabled = YES;
        [self.view addSubview:tableView];
        
        tableView;
    });
    self.myTableView.backgroundColor = [UIColor whiteColor];
    self.myTableView.tableHeaderView = [self customHeaderView];
    self.myTableView.tableFooterView = [self customFooterView];
    
    [self.view addSubview:self.cancelButton];
}
- (void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    [self.navigationController setNavigationBarHidden:YES animated:YES];
}
- (void)viewWillDisappear:(BOOL)animated{
    [super viewWillDisappear:animated];
    [self.view endEditing:YES];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
}





#pragma mark UITableViewDataSource
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return 2;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    __weak typeof(self) weakSelf = self;

    XJYLoginTextCell *cell = [tableView dequeueReusableCellWithIdentifier:kCellIdentifier_Input_OnlyText_Cell_Text forIndexPath:indexPath];
    if (indexPath.row == 0) {
        cell.textField.keyboardType = UIKeyboardTypeEmailAddress;
        [cell setPlaceholder:@"用户名" value:self.myLogin.name];
        cell.textValueChangedBlock = ^(NSString *valueStr){
            weakSelf.nameString = valueStr;
            weakSelf.myLogin.name = valueStr;
            NSLog(@"nameString=%@",weakSelf.nameString);
        };


    }else if (indexPath.row == 1){
        [cell setPlaceholder:@" 密码" value:self.myLogin.password];
        cell.textField.secureTextEntry = YES;
        cell.textValueChangedBlock = ^(NSString *valueStr){
            weakSelf.passwordString = valueStr;
            weakSelf.myLogin.password = valueStr;
            NSLog(@"passwordString=%@",weakSelf.myLogin.password);

        };
    }
    return cell;
}

#pragma mark UITableViewDelegate


- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    NSLog(@"select cell at %lD",(long)indexPath.row);
    XJYLoginTextCell *cell = [tableView cellForRowAtIndexPath:indexPath];
    [cell.textField setUserInteractionEnabled:YES];
    [cell.textField becomeFirstResponder];
}


#pragma mark lazyLoading

- (UIButton *)cancelButton{
    UIButton *cancelButton  = [[UIButton alloc]initWithFrame:RectMake_LFL(10, 0, 45, 100)];
    [cancelButton setTitle:@"取消" forState:UIControlStateNormal];
    [cancelButton.titleLabel setFont:[UIFont systemFontOfSize:13]];
    [cancelButton addTarget:self action:@selector(cancelButtonClicked:) forControlEvents:UIControlEventTouchUpInside];
    [cancelButton setTintColor:[UIColor clearColor]];
    return cancelButton;
}

- (UIButton *)thirdPartyLoginWeiboButton{
    
    if(!_thirdPartyLoginWeiboButton){
        _thirdPartyLoginWeiboButton = [[UIButton alloc]initWithFrame:RectMake_LFL(iPhone6W/4 - 25, 150, 50, 50)];
        //    [thirdPartyLoginWeiboButton setTitle:@"wb" forState:UIControlStateNormal];
        [_thirdPartyLoginWeiboButton setImage:[UIImage imageNamed:@"wb"] forState:UIControlStateNormal];
        //target action
        [_thirdPartyLoginWeiboButton addTarget:self action:@selector(thirdPartyLoginWeiboButtonClicked:) forControlEvents:UIControlEventTouchUpInside];
        //layer
        _thirdPartyLoginWeiboButton.layer.cornerRadius = 25;
        _thirdPartyLoginWeiboButton.layer.masksToBounds = YES;
        
    }
    return _thirdPartyLoginWeiboButton;
}

- (UIButton *)thirdPartyLoginWeixinButton{
    

    UIButton *thirdPartyLoginWeixinButton = [[UIButton alloc]initWithFrame:RectMake_LFL(iPhone6W/4*2-25, 150, 50, 50)];
    [thirdPartyLoginWeixinButton setImage:[UIImage imageNamed:@"wx"] forState:UIControlStateNormal];
//    [thirdPartyLoginWeixinButton setTitle:@"wx" forState:UIControlStateNormal];
    
    //layer
    thirdPartyLoginWeixinButton.layer.cornerRadius = 25;
    thirdPartyLoginWeixinButton.layer.masksToBounds = YES;
    
    //target action
    [thirdPartyLoginWeixinButton addTarget:self action:@selector(thirdPartyLoginWeixinButtonClicked:) forControlEvents:UIControlEventTouchUpInside];
    return thirdPartyLoginWeixinButton;
}

- (UIButton *)thirdPartyLoginQQButton{
    UIButton *thirdPartyLoginQQButton = [[UIButton alloc]initWithFrame:RectMake_LFL(iPhone6W/4*3-25, 150, 50, 50)];
//    [thirdPartyLoginQQButton setTitle:@"qqq" forState:UIControlStateNormal];
    [thirdPartyLoginQQButton setImage:[UIImage imageNamed:@"qqq"] forState:UIControlStateNormal];
    
    //layer
    thirdPartyLoginQQButton.layer.cornerRadius = 25;
    thirdPartyLoginQQButton.layer.masksToBounds = YES;
    
    //target action
    [thirdPartyLoginQQButton addTarget:self action:@selector(thirdPartyLoginQQButtonClicked:) forControlEvents:UIControlEventTouchUpInside];
    return thirdPartyLoginQQButton;
}

- (UIImageView *)bgBlurredView{
    UIImageView *bgBlurredView = [[UIImageView alloc]initWithFrame:CGRectMake(0, 0, ScreenW, ScreenH)];
    bgBlurredView.image = [UIImage imageNamed:@"moutain"];
    
    if (!UIAccessibilityIsReduceTransparencyEnabled()) {
        bgBlurredView.backgroundColor = [UIColor clearColor];
        
        UIBlurEffect *blurEffect = [UIBlurEffect effectWithStyle:UIBlurEffectStyleDark];
        UIVisualEffectView *blurEffectView = [[UIVisualEffectView alloc] initWithEffect:blurEffect];
        blurEffectView.frame = bgBlurredView.bounds;
        blurEffectView.autoresizingMask = UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight;
        
        [bgBlurredView addSubview:blurEffectView];
    } else {
        bgBlurredView.backgroundColor = [UIColor blackColor];
    }
    
    return bgBlurredView;
}


- (XJYLogin *)myLogin{
    if (!_myLogin) {
        _myLogin = [[XJYLogin alloc]init];
    }
    return  _myLogin;
}

#pragma mark - Table view Header Footer
- (UIView *)customHeaderView{
    CGFloat iconUserViewWidth;
    if (kDevice_Is_iPhone6Plus) {
        iconUserViewWidth = 100;
    }else if (kDevice_Is_iPhone6){
        iconUserViewWidth = 90;
    }else{
        iconUserViewWidth = 75;
    }
    
    UIView *headerV = [[UIView alloc] initWithFrame:CGRectMake(0, 0, kScreen_Width, kScreen_Height/3)];
    
    _iconUserView = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, iconUserViewWidth, iconUserViewWidth)];
    _iconUserView.contentMode = UIViewContentModeScaleAspectFit;
    _iconUserView.layer.masksToBounds = YES;
    _iconUserView.layer.cornerRadius = _iconUserView.frame.size.width/2;
    _iconUserView.layer.borderWidth = 2;
    _iconUserView.layer.borderColor = [UIColor whiteColor].CGColor;
    
    [headerV addSubview:_iconUserView];
    [_iconUserView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.size.mas_equalTo(CGSizeMake(iconUserViewWidth, iconUserViewWidth));
        make.centerX.equalTo(headerV);
        make.centerY.equalTo(headerV).offset(30);
    }];
    [_iconUserView setImage:[UIImage imageNamed:@"header1"]];
    return headerV;
}

- (UIView *)customFooterView{
    UIView *footerV = [[UIView alloc] initWithFrame:CGRectMake(0, 0, kScreen_Width, 250)];
    
    self.loginButton = ({
        _loginButton = [[FUIButton alloc]initWithFrame:RectMake_LFL(iPhone6W/2 - 150, 30, 300, 40)];
        self.loginButton.buttonColor = [UIColor greenSeaColor];
        self.loginButton.titleLabel.font = [UIFont iconFontWithSize:14];
        [self.loginButton setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
        self.loginButton.cornerRadius = 22.0f;
        [self.loginButton setTitle:@"登陆" forState:UIControlStateNormal];
        [self.loginButton addTarget:self action:@selector(sendLogin:) forControlEvents:UIControlEventTouchUpInside];
        [footerV addSubview:_loginButton];
        _loginButton;
    });
    
    
    self.cannotLoginButton = ({
        _cannotLoginButton = [[FUIButton alloc]initWithFrame:RectMake_LFL(iPhone6W/2 - 150, 80, 300, 40)];
        _cannotLoginButton.buttonColor = [UIColor clearColor];
        _cannotLoginButton.titleLabel.font = [UIFont iconFontWithSize:12];
        [_cannotLoginButton setTitle:@"找回密码" forState:UIControlStateNormal];
        [_cannotLoginButton setTitleColor:[UIColor lightGrayColor] forState:UIControlStateNormal];
        [_cannotLoginButton addTarget:self action:@selector(cannotLoginBtnClicked:) forControlEvents:UIControlEventTouchUpInside];
        [footerV addSubview:_cannotLoginButton];
        _cannotLoginButton;
    });
    
    [footerV addSubview:self.thirdPartyLoginWeiboButton];
    [footerV addSubview:self.thirdPartyLoginWeixinButton];
    [footerV addSubview:self.thirdPartyLoginQQButton];
    

    footerV.backgroundColor = [UIColor clearColor];
    return footerV;
}


#pragma mark ButtonClicked

- (void)sendLogin:(UIButton *)button{
//    [[NSNotificationCenter defaultCenter]postNotification:[NSNotification notificationWithName:@"resignLoginTextCellKeyboradFirstResponder" object:nil]];
    NSLog(@"CLicked");
    if ([_nameString  isEqual: @""]||[_passwordString isEqual:@""]) {
        NSLog(@"失败");
    }else{
        [self.view endEditing:YES];
        [[XJYNetApiClient shareXJYNetClient] loginWithLoginPath:[self.myLogin toPath] Params:[self.myLogin toParams] andBlock:^(id data, NSError *error) {
            if(!error){
                [XJYLogin doLogin:data];
            }
        }];
    }

    
}

- (void)cannotLoginBtnClicked:(UIButton *)button{
    NSLog(@"Clicked");

}

- (void)cancelButtonClicked:(UIButton *)button{
    NSLog(@"cancel button clicked");
    [self dismissViewControllerAnimated:YES completion:^{
    }];
    
}

#pragma mark thirdPartyLogin
- (void)thirdPartyLoginWeiboButtonClicked:(UIButton *)button{
    [[XJYNetApiClient shareXJYNetClient] weiboLogin];
}

- (void)thirdPartyLoginWeixinButtonClicked:(UIButton *)button{
    [[XJYNetApiClient shareXJYNetClient] weixinLogin];
}

- (void)thirdPartyLoginQQButtonClicked:(UIButton *)button{
    [[XJYNetApiClient shareXJYNetClient] qqLogin];
}


#pragma mark Notification Action

- (void)loginFailed{
    MBProgressHUD *hud = [MBProgressHUD showHUDAddedTo:self.view animated:YES];
    hud.mode = MBProgressHUDModeText;
    hud.labelText = NSLocalizedString(@"用户名密码不匹配!", @"HUD message title");
    hud.yOffset = 100;;
    hud.xOffset = 0.f;
    [hud hide:YES afterDelay:1.f];
}



@end
